/*
 * @Author: zhangyang
 * @Date: 2021-11-27 15:19:39
 * @LastEditTime: 2021-11-28 15:13:44
 * @Description: 入口文件
 */
const { WebSocketServer } = require('ws');
const { Gpio } = require('onoff');

const button = new Gpio(21, 'out');

const ws = new WebSocketServer({ port: 9528 });

const getStatus = () => button.readSync();


ws.on('connection', async (socket) => {
  socket.on('message', (msg) => {
    try {
      const { method, value } = JSON.parse(msg);
      if (method === 'get') {
        socket.send(JSON.stringify({ isOn: getStatus() }));
      } else {
        button.writeSync(value);
        socket.send(JSON.stringify({ isOn: getStatus() }));
      }
    } catch (error) {
      console.error(error);
    }
  })
  socket.send(JSON.stringify({ isOn: getStatus() }));
});
console.log('websocket 运行中......');
// let isOn = false;

process.on('SIGINT', () => {
  console.log('按下了 Ctrl + C，程序即将终止......');
  button.writeSync(0);
  delete button;
  process.exit();
});

// try {
//   setInterval(() => {
//     isOn = !isOn;
//     // console.log(isOn);
//     button.writeSync(+isOn);
//   }, 1000);
// } catch (error) {
//   console.log(eror);
// }
